package net.threeple.springjdbc.helper;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;

public class SqlParameterMapperImpl implements SqlParameterMapper {
	final Logger logger = LoggerFactory.getLogger(SqlParameterMapperImpl.class);
	
	@Override
	public MapSqlParameterSource addParametersFrom(Object object) {
		MapSqlParameterSource paramSource = new MapSqlParameterSource();
		BeanWrapper bean = new BeanWrapperImpl(object);
		String[] fieldsName = getFieldsName(object);
		for(String fieldName : fieldsName){
			Object value = bean.getPropertyValue(fieldName);
			if(value == null) {
				paramSource.addValue(fieldName, null);
				continue;
			}
			if(bean.getPropertyType(fieldName).isEnum()) {
				paramSource.addValue(fieldName, value.toString());
			} else {
				paramSource.addValue(fieldName, value);
			}
		}
		return paramSource;
	}
	
	private String[] getFieldsName(Object object) {
		List<String> fieldList = new ArrayList<String>();
		Class<?> clazz = object.getClass();
		Field[] fields = clazz.getDeclaredFields();
		for(Field field : fields) {
			fieldList.add(field.getName());
		}
		return fieldList.toArray(new String[]{});
	}

}
